# -*- coding: utf-8 -*-
from openerp.osv import osv
from openerp.osv import fields
import datetime


class product_template(osv.osv):
    _inherit = 'product.template'

    def _get_template_by_product(self, cr, uid, ids, context=None):
        res = []
        for product in self.browse(cr, uid, ids, context=context):
            res.append(product.product_tmpl_id.id)

        return res

    def _get_is_end_time(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        for template in self.browse(cr, uid, ids, context=context):
            res.update({
                template.id: all(product.is_end() for product in template.product_variant_ids)
            })

        return res

    _columns = {
        'is_end_time': fields.function(_get_is_end_time, type='boolean', string=u'是否过期', store={
                'product.template': (lambda self, cr, uid, ids, ctx=None: ids, ['product_variant_ids'], 10),
                'product.product': (_get_template_by_product, ['start_sale_time', 'end_sale_time', 'minimum_quantity'], 10),
            }),
    }

    def get_template_count(self, cr, uid, categ_id=None, brand_id=None, context=None):
        extra_domain = ''

        if categ_id:
            extra_domain += '''
                AND id in (
                    select product_template_id from product_public_category_product_template_rel
                    where product_public_category_id = %s
                )
            ''' % str(categ_id)

        if brand_id:
            extra_domain += '''
                AND product_brand_id = %s
            ''' % str(brand_id)

        cr.execute('''
            SELECT COUNT(*) FROM product_template
            WHERE active = True AND company_id = 1 AND sale_ok = True AND type != 'service' %s
        ''' % extra_domain)

        try:
            count = cr.fetchall()[0][0]
        except IndexError:
            count = 0

        return count

    def get_evaluations(self, cr, uid, template_id, context=None):
        evaluation_obj = self.pool.get('order.evaluation')

        evaluation_ids = evaluation_obj.search(cr, uid, [('line_id.product_id.product_tmpl_id', '=', template_id)], context=context)

        res = []
        for evaluation in evaluation_obj.browse(cr, uid, evaluation_ids, context=context):
            res.append({
                    'id': evaluation.id,
                    'user_id': evaluation.user_id.id,
                    'username': evaluation.is_anonymous and self.pool.get('sale.order')._anonymous(evaluation.user_id.name) or evaluation.user_id.name,
                    'description': evaluation.description,
                    'variants': ','.join(value.attribute_id.name + ':' + value.name for value in evaluation.line_id.product_id.attribute_value_ids),
                })

        return res or False

    def get_evaluation(self, cr, uid, template_id, context=None):
        evaluation_obj = self.pool.get('order.evaluation')

        evaluation_ids = evaluation_obj.search(cr, uid, [('line_id.product_id.product_tmpl_id', '=', template_id)], limit=1, context=context)

        # @正翔 使用sql的方式来获取当前产品的所有评价数量，可能会加快点速度？
        cr.execute('''
            SELECT COUNT(*) FROM order_evaluation oe
            LEFT JOIN sale_order_line sol ON oe.line_id = sol.id
            LEFT JOIN product_product pp ON sol.product_id = pp.id
            LEFT JOIN product_template pt ON pp.product_tmpl_id = pt.id

            WHERE pt.id = %s AND oe.user_type = 'buyer'
        ''', (template_id, ))

        try:
            count = cr.fetchall()[0][0]
        except IndexError:
            count = 0

        if evaluation_ids:
            evaluation = evaluation_obj.browse(cr, uid, evaluation_ids[0], context=context)
            return {
                'id': evaluation.id,
                'count': count,
                'user_id': evaluation.user_id.id,
                'username': evaluation.is_anonymous and self.pool.get('sale.order')._anonymous(evaluation.user_id.name) or evaluation.user_id.name,
                'description': evaluation.description,
                'variants': ','.join(value.attribute_id.name + ':' + value.name for value in evaluation.line_id.product_id.attribute_value_ids),
            }
        else:
            return False

    def get_images(self, cr, uid, template_id, context=None):
        images = []
        for template in self.browse(cr, uid, template_id, context=context):
            for product in template.product_variant_ids:
                if not product.image_ids:
                    images.append(
                        {'product_id': product.id, 'image': '/website/image/product.template/' + str(template.id) + '/image'})

                for gallery in product.image_ids:
                    if gallery.link:
                        images.append(
                            {'product_id': product.id, 'image': gallery.url})
                    else:
                        images.append(
                            {'product_id': product.id, 'image': '/website/image/product.images/' + str(gallery.id) + '/file'})

        return images or False

    def get_images_for_index(self, cr, uid, context=None):
        return self.pool.get('weixin.advertising.wall').get_image_and_url(cr, uid, context=context)

    # TODO 首页活动墙中使用的图片，暂时不做处理
    def get_events_for_index(self, cr, uid, context=None):
        return self.pool.get('weinxin.homepage.categories').get_image_and_url(cr, uid, context=context)


class product_product(osv.osv):
    _inherit = 'product.product'

    def is_end(self, cr, uid, ids, context=None):
        if not ids or len(ids) != 1:
            raise osv.except_osv(u'错误', u'该判定函数只能对一个具体的产品使用')

        datetime_now = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        for product in self.browse(cr, uid, ids, context=context):
            if product.end_sale_time and product.end_sale_time < datetime_now:
                return True

        return False

    def _get_reserve_quantity(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        for product in self.browse(cr, uid, ids, context=context):
            if product.start_sale_time or product.end_sale_time:
                domain = [('product_id', '=', product.id)]
                if product.start_sale_time:
                    domain.append(('create_date', '>', product.start_sale_time))

                if product.end_sale_time:
                    domain.append(('create_date', '<', product.end_sale_time))

                carts = self.pool.get('shopping.cart.line').search_read(cr, uid, domain +
                    [('state', '=', 'draft')], ['product_uom_qty'], context=context)

                orders = self.pool.get('sale.order.line').search_read(cr, uid, domain +
                        [('order_id.state', '!=', 'cancel')], ['product_uom_qty'], context=context)

                res.update({
                    product.id: sum(cart.get('product_uom_qty', 0) for cart in carts) + sum(order.get('product_uom_qty', 0) for order in orders)
                })
            else:
                res.update({product.id: 0})

        return res

    _columns = {
        'start_sale_time': fields.datetime(u'起始销售时间'),
        'end_sale_time': fields.datetime(u'结束销售时间'),
        'minimum_quantity': fields.integer(u'起订数量'),
        'reserve_quantity': fields.function(_get_reserve_quantity, type='integer', string=u'预订数量'),
    }
